package cn.com.gas.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.constants.GasConstants;
import cn.com.gas.entity.GasStationDeptEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasStationDeptService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 加油站信息
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-04-12 16:28:51
 */
@Controller
@RequestMapping("/gas/stationinfo")
public class GasStationinfoController {
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private GasStationDeptService gasStationDeptService;
	
	// @Autowired
	// private GasServerAreaService gasServerAreaService;
	// @Autowired
	// private GasServerChannelService gasServerChannelService;

	@ApiOperation(value = "取消分析")
	@PostMapping("/analysisCancel")
	// @RequiresPermissions("gasStationinfo:update")
	@ResponseBody
	public DataResult analysisCancel(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
		String currentUserId = httpSessionService.getCurrentUserId();
		Date date = new Date();
		for (String id : ids) {
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(id);
			stationinfo.setIsAnalyse("");
			stationinfo.setUpdateId(currentUserId);
			stationinfo.setUpdateTime(date);
			gasStationinfoService.updateById(stationinfo);

			// 更新下一级的 isAnalyse
			LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(GasStationinfoEntity::getPid, id);
			List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);
			for (GasStationinfoEntity gasStationinfoEntity : list) {
				gasStationinfoEntity.setIsAnalyse("");
				gasStationinfoEntity.setUpdateId(currentUserId);
				gasStationinfoEntity.setUpdateTime(date);
				gasStationinfoService.updateById(gasStationinfoEntity);

			}

		}
		;

		return DataResult.success();
	}

	@ApiOperation(value = "确认分析")
	@PostMapping("/analysisConfirm")
	// @RequiresPermissions("gasStationinfo:update")
	@ResponseBody
	public DataResult analysisConfirm(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
		String currentUserId = httpSessionService.getCurrentUserId();
		Date date = new Date();
		for (String id : ids) {
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(id);
			stationinfo.setIsAnalyse("Y");
			stationinfo.setUpdateId(currentUserId);
			stationinfo.setUpdateTime(date);
			gasStationinfoService.updateById(stationinfo);

			// 更新下一级的 isAnalyse
			LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(GasStationinfoEntity::getPid, id);
			List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);
			for (GasStationinfoEntity gasStationinfoEntity : list) {
				gasStationinfoEntity.setIsAnalyse("Y");
				gasStationinfoEntity.setUpdateId(currentUserId);
				gasStationinfoEntity.setUpdateTime(date);
				gasStationinfoService.updateById(gasStationinfoEntity);

			}

		}
		;

		return DataResult.success();

	}

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	// @RequiresPermissions("gasStationinfo:update")
	@ResponseBody
	public DataResult update(@RequestBody GasStationinfoEntity gasStationinfo) {
		
		// String location = gasStationinfo.getGasLocation();
		// String coverage = gasStationinfo.getGasCoverage();
		
		/*if(!isInteger(location)){
			return DataResult.fail("加油位数填写有问题!");
		};*/
		
		/*if(!isInteger(coverage)){
			return DataResult.fail("覆盖位数填写有问题!");
		};*/
		
		gasStationinfoService.updateCurrentAndNextLevelById(gasStationinfo);
		return DataResult.success();
	}

	@GetMapping("/tree")
	@ApiOperation(value = "树型组织列表接口")
	@ResponseBody
	public DataResult getTree(@RequestParam(required = false) String id) {
		return DataResult.success(gasStationinfoService.treeList(id));
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/list")
	@ApiOperation(value = "加油站信息列表")
	@ResponseBody
	public DataResult pageInfo(@RequestBody GasStationinfoEntity vo) {

		Page page = new Page(vo.getPage(), vo.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(vo.getId())) {
			if ("cam".equals(vo.getType())) {
				queryWrapper.eq(GasStationinfoEntity::getId, vo.getId());
			} else {
				queryWrapper.eq(GasStationinfoEntity::getPid, vo.getId());
			}
		} else {
			return DataResult.fail("请选择左侧区域树！");
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}

		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();

		for (GasStationinfoEntity gasStationinfoEntity : records) {
			String name = gasStationinfoEntity.getName();

			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(name));
				// gasStationinfoEntity.setOnline(TsBqUtils.isOnline(name, gasStationinfoEntity.getOnline()));
			} else {
				
				String iconSkin = gasStationinfoEntity.getIconSkin();
				if(TsBqUtils.isNotNull(iconSkin)){
					gasStationinfoEntity.setOnline(
							iconSkin.equals(GasConstants.ICON_SKIN_ON) ? GasConstants.ON_LINE : GasConstants.OFF_LINE);
				}
				
			}

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/list1")
	@ApiOperation(value = "加油站信息列表")
	@ResponseBody
	public DataResult pageInfo1(@RequestBody GasStationinfoEntity vo) {

		String currentDeptId = httpSessionService.getCurrentDeptId();

		Page page = new Page(vo.getPage(), vo.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		// TODO
		// queryWrapper.eq(GasStationinfoEntity::getPid,
		// "5c8baa4b-081f-41aa-a549-2235b786c7c7");
		// queryWrapper.eq(GasStationinfoEntity::getType, "group");
		// queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
// 
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		}else{
			//  省局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 3));
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}
		
		if (TsBqUtils.isNotNull(vo.getTaxpayerCode())) {
			queryWrapper.like(GasStationinfoEntity::getTaxpayerCode, vo.getTaxpayerCode());
		}
		
		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();

		for (GasStationinfoEntity gasStationinfoEntity : records) {
			String stationinfoname = gasStationinfoEntity.getName();
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(stationinfoname));
			}

			String taxorgcode = gasStationinfoEntity.getTaxorgcode();
			SysDept sysDept = deptService.getById(taxorgcode);
			if (TsBqUtils.isNotNull(sysDept)) {
				String name = sysDept.getName();
				gasStationinfoEntity.setTaxorgName(name);
				
			}

			// gasStationinfoEntity.setOnline(TsBqUtils.isOnline(stationinfoname, gasStationinfoEntity.getOnline()));
			
		}

		return DataResult.success(iPage);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/list2")
	@ApiOperation(value = "加油站信息明细列表")
	@ResponseBody
	public DataResult pageInfo2(@RequestBody GasStationinfoEntity vo) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();

		Page page = new Page(vo.getPage(), vo.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

		// TODO
		// queryWrapper.eq(GasStationinfoEntity::getPid,
		// "5c8baa4b-081f-41aa-a549-2235b786c7c7");
		// queryWrapper.eq(GasStationinfoEntity::getType, "group");
		// queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		}else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 市局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));

		} else {
			// 省局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}

		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);
		List<GasStationinfoEntity> records = iPage.getRecords();
		for (GasStationinfoEntity gasStationinfoEntity : records) {
			// 处理加油站 名称
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}
			// 税务机关
			String taxorgcode = gasStationinfoEntity.getTaxorgcode();
			SysDept sysDept = deptService.getById(taxorgcode);
			
			if(TsBqUtils.isNotNull(sysDept)){
				gasStationinfoEntity.setTaxorgName(sysDept.getName());
			}else{
				gasStationinfoEntity.setTaxorgName(taxorgcode);
			}
			

			// 计算累计金额
			BigDecimal result = new BigDecimal(0);

			String id = gasStationinfoEntity.getId();

			LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper1 = Wrappers.lambdaQuery();
			queryWrapper1.eq(GasStaytimeResultEntity::getStationId, id);

			if (!StringUtils.isEmpty(vo.getCreateTimeStart())) {
				queryWrapper1.ge(GasStaytimeResultEntity::getMessageDisappear, sdf.parse(vo.getCreateTimeStart() + " 00:00:00"));
			}else{
				return DataResult.success("start-MessageDisappear不能为空！");
			}
			
			if (!StringUtils.isEmpty(vo.getCreateTimeEnd())) {
				queryWrapper1.le(GasStaytimeResultEntity::getMessageDisappear, sdf.parse(vo.getCreateTimeEnd() + " 23:59:59"));
			}else{
				return DataResult.success("end-MessageDisappear不能为空！");
			}

			List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper1);
			for (GasStaytimeResultEntity gasStaytimeResultEntity : list) {
				String price = gasStaytimeResultEntity.getPrice();
				BigDecimal _price = new BigDecimal(price);
				result = result.add(_price);
			}

			gasStationinfoEntity.setPrice(result.toString());

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/list3")
	@ApiOperation(value = "加油站信息维护列表")
	@ResponseBody
	public DataResult pageInfo3(@RequestBody GasStationinfoEntity vo) {
		
		String taxorgcode = vo.getTaxorgcode();
		
		String currentDeptId = httpSessionService.getCurrentDeptId();
		
		List<GasStationDeptEntity> list = gasStationDeptService.list();
		List<String> ids = new ArrayList<String>();
		for (GasStationDeptEntity gasStationDeptEntity : list) {
			String endangerId = gasStationDeptEntity.getEndangerId();
			String regionId = gasStationDeptEntity.getRegionId();
			ids.add(endangerId);
			ids.add(regionId);
		}
		
		List<String> _ids = ids.stream().distinct().collect(Collectors.toList());
		
		Page page = new Page(vo.getPage(), vo.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

		queryWrapper.eq(GasStationinfoEntity::getType, "group");
		if (TsBqUtils.isNotNull(taxorgcode)) {
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, taxorgcode);
		}else{
		
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
				
			} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
				// 市局 
				queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			
			}else{
				// 省局
				
			}
		}
		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}
		
		if (TsBqUtils.isNotNull(vo.getTaxpayerCode())) {
			queryWrapper.like(GasStationinfoEntity::getTaxpayerCode, vo.getTaxpayerCode());
		}
		
		queryWrapper.ne(GasStationinfoEntity::getPid, "0");
		queryWrapper.notIn(GasStationinfoEntity::getId, _ids);
		
		
		
		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();

		for (GasStationinfoEntity gasStationinfoEntity : records) {
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}

			SysDept sysDept = deptService.getById(gasStationinfoEntity.getTaxorgcode());
			if (TsBqUtils.isNotNull(sysDept)) {
				String name = sysDept.getName();
				gasStationinfoEntity.setTaxorgName(name);

			}
		}

		return DataResult.success(iPage);
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/goOnlineList")
	@ApiOperation(value = "加油站上线列表")
	@ResponseBody
	public DataResult goOnlineList(@RequestBody GasStationinfoEntity vo) {
		
		String currentDeptId = httpSessionService.getCurrentDeptId();
		
		List<GasStationDeptEntity> list = gasStationDeptService.list();
		List<String> ids = new ArrayList<String>();
		for (GasStationDeptEntity gasStationDeptEntity : list) {
			String endangerId = gasStationDeptEntity.getEndangerId();
			String regionId = gasStationDeptEntity.getRegionId();
			ids.add(endangerId);
			ids.add(regionId);
		}
		
		List<String> _ids = ids.stream().distinct().collect(Collectors.toList());
		
		Page page = new Page(vo.getPage(), vo.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

		queryWrapper.eq(GasStationinfoEntity::getType, "group");
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局 
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		}else{
			// 省局
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}
		
		queryWrapper.ne(GasStationinfoEntity::getPid, "0");
		queryWrapper.notIn(GasStationinfoEntity::getId, _ids);
		
		
		String goOnline = vo.getGoOnline();
		
		if(TsBqUtils.isNotNull(goOnline)){
			if(GasConstants.ON_LINE.equals(goOnline)){
				// 上线 1
				queryWrapper.apply("gas_stationinfo.id IN ( "
								    +"SELECT "
								    +"c.id "
								    +"FROM "
								    +"gas_stationinfo c "
								    +"WHERE "
								    +"c.id IN ( SELECT b.pid FROM gas_stationinfo b WHERE b.id IN ( SELECT a.camid FROM gas_server_area a ) ) "
								    +")");

			}else if(GasConstants.OFF_LINE.equals(goOnline)){
				// 未上线 0
				queryWrapper.apply("gas_stationinfo.id NOT IN ( "
					    +"SELECT "
					    +"c.id "
					    +"FROM "
					    +"gas_stationinfo c "
					    +"WHERE "
					    +"c.id IN ( SELECT b.pid FROM gas_stationinfo b WHERE b.id IN ( SELECT a.camid FROM gas_server_area a ) ) "
					    +")");
			}
			
		}
		
		
		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();

		for (GasStationinfoEntity gasStationinfoEntity : records) {
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}

			String taxorgcode = gasStationinfoEntity.getTaxorgcode();
			SysDept sysDept = deptService.getById(taxorgcode);
			if (TsBqUtils.isNotNull(sysDept)) {
				String name = sysDept.getName();
				gasStationinfoEntity.setTaxorgName(name);

			}
		}

		return DataResult.success(iPage);
	}
	
	
	
	public static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
	
}
